<?php

namespace app\domain\admin;

use app\model\Data;

class DashBoardDomain extends CommonDomain
{
    public function dashboard(): array
    {
        try {
            $cacheKey = "weatherDashboardData";
            $cacheData = json_decode(cache($cacheKey) ?? '', true);
            if ($cacheData) {
                return $cacheData;
            }

            $timestamp = time();

            $date = date('Y_m', time());
            $model = app(Data::class)->table("ice_data_{$date}");
            $currentMonthDays = date('t');
            $currentMonthStart = date('Y-m-01', $timestamp);
            $currentMonthEnd = date("Y-m-{$currentMonthDays} 23:59:59", $timestamp);
            $dataTotalMonth = $model->whereTime('receive_time', 'between', [$currentMonthStart, $currentMonthEnd])->count();
            $dataTotalToday = $model->whereDay('receive_time')->count();

            $lastDay = strtotime("-1 day", $timestamp);
            $monthCondition = [$lastDay, $timestamp];
            $deviceDataList = $model
                ->withoutField(['original_data'])
                ->whereTime('receive_time', 'between', $monthCondition)
                ->order('id DESC')
                ->limit(2000)
                ->select();

            $temperatureData = $waterFilmData = [];
            $deviceDataList->filter(function ($row) use (&$temperatureData, &$waterFilmData) {
                $receiveTime = date('H:i', strtotime($row['receive_time']));
                $temperatureData[$row['serial_number']]['date'][] = $receiveTime;
                $temperatureData[$row['serial_number']]['data'][] = $row['temperature'];

                $waterFilmData[$row['serial_number']]['date'][] = $receiveTime;
                $waterFilmData[$row['serial_number']]['data'][] = $row['water_film'];
            });

            foreach ($temperatureData as $key => $value) {
                $temperatureData[$key]['date'] = array_reverse($value['date']);
                $temperatureData[$key]['data'] = array_reverse($value['data']);
            }

            foreach ($waterFilmData as $key => $value) {
                $waterFilmData[$key]['date'] = array_reverse($value['date']);
                $waterFilmData[$key]['data'] = array_reverse($value['data']);
            }

            $returnData = [
                'dataTotalMonth' => $dataTotalMonth,
                'dataTotalToday' => $dataTotalToday,
                'temperature' => $temperatureData,
                'waterFilm' => $waterFilmData,
            ];
            cache($cacheKey, json_encode($returnData, 320), 3600);

            return $returnData;
        } catch (\Exception $e) {
            return [
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
            ];
        }
    }

    public function getNewData()
    {
        try {
            $serialNumber = ['JL20250124001', 'JL20250124002', 'JL20250124003', 'JL20250124004'];
            $result = [];

            $date = date('Y_m', time());
            $tableName = "ice_data_{$date}";
            foreach ($serialNumber as $key => $value) {
                $model = app(Data::class)->table($tableName);
                $result[] = $model->where(['serial_number' => $value])->order('id DESC')->find();
            }

            return $result;
        } catch (\Exception $e) {
        }
    }
}